﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using com.fmtx.IDal;
using com.fmtx.Model;
using fmtx.Framework.DALFactory;
using fmtx.Framework.DESC;
using System.Configuration;
using fmtx.Framework.OpenOAuth;
using System.Collections;

namespace website.Areas.Website.Controllers
{
    public class LoginController : BaseController
    {
        //
        // GET: /Website/Login/
        private IUserInfo userinfo = DataAccess<IUserInfo>.GetObject();
        private IOAuthUser _oauth = DataAccess<IOAuthUser>.GetObject();

        #region 登录
        #region 登录页面
        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        #endregion

        #region http登录
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public ActionResult DoLogin(LogOnModel model, string callback)
        {
            if (ModelState.IsValid)
            {
                var oauth = Session["oauth_user"] as Hashtable;
                var bean = userinfo.Login(model.UserName, DESCHandler.MD5_32(model.Password));
                if (bean != null && bean.Uid > 0)
                {
                    LoginModel.SetUserInfo(bean, model.RememberMe ? 360 : 0);
                    if (oauth != null)
                    {
                        OAuthUser oath = new OAuthUser();
                        oath.Uid = bean.Uid;
                        oath.OpenId = oauth["openid"].ToString();
                        oath.Type = (OAuthType)oauth["type"];
                        oath.AccessToken = oauth["access_token"].ToString();
                        oath.OutTime = DateTime.Now.AddSeconds(Convert.ToInt64(oauth["expires"]));
                        if (string.IsNullOrEmpty(bean.Header) && !string.IsNullOrEmpty(Request["header"]))
                        {
                            var header = StaticCs.SaveTempPic(StaticCs.DownImageToTemp(Request["header"]));
                            bean.Header = header;
                            userInfo.Header = header;
                            userinfo.Update(bean);
                        }
                        _oauth.Add(oath);
                        Session["oauth_user"] = null;
                        StaticCs.RemoveUserFolder(bean.Uid);
                    }
                    if (!string.IsNullOrEmpty(callback))
                    {
                        return Redirect(callback);
                    }
                    else
                    {
                        return Redirect("/");
                    }
                }
                ViewBag.msg = "登录失败！";
            }
            return View("index",model);
        }
        #endregion

        #region ajax登录
        /// <summary>
        /// ajax登录
        /// </summary>
        /// <param name="model"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public ActionResult DojsLogin(LogOnModel model)
        {
            if (ModelState.IsValid)
            {
                var bean = userinfo.Login(model.UserName, DESCHandler.MD5_32(model.Password));
                if (bean != null && bean.Uid > 0)
                {
                    LoginModel.SetUserInfo(bean, model.RememberMe ? 360 : 0);
                    return Json(new { Uid = bean.Uid, Uname = bean.Name, Header = bean.Header });
                }
            }
            return Json(new { error = 1001 });
        }
        #endregion 


        #endregion

        #region 统一登录方法
        /// <summary>
        /// 统一登录方法
        /// </summary>
        /// <param name="user"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        private ActionResult doLogin(UserInfo user, string callback)
        {
            LoginModel.SetUserInfo(user);
            if (!string.IsNullOrEmpty(callback) || Session["Login_Callback"] != null)
            {
                return Redirect(callback ?? Session["Login_Callback"].ToString());
            }
            else
            {
                return Redirect("/");
            }
        } 
        #endregion

        #region 第三方登录
        /// <summary>
        /// qq登录
        /// </summary>
        /// <returns></returns>
        public ActionResult QQLogin(string callback)
        {
            Session["Login_Callback"] = callback;
            QQOAuth oauth = new QQOAuth(ConfigurationManager.AppSettings["qq_appKey"], ConfigurationManager.AppSettings["qq_appSecret"], ConfigurationManager.AppSettings["qq_callBackURI"]);
            Session["qq_oauth"] = oauth;
            return Redirect(oauth.ShwoLoginUrl());
        }

        /// <summary>
        /// qqapi回传页面
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult QQCallback(string code, string state)
        {
            if (code != null)
            {
                var qqoauth = Session["qq_oauth"] as QQOAuth;
                var getat=qqoauth.GetAccessToken(code);
                var access_token = getat.Accesstoken;
                var expires = getat.Expires;
                var openid = qqoauth.GetOpenId(access_token);
                Session["qq_oauth"] = null;
                QQUser qquser= qqoauth.GetUserInfo(access_token, openid);
                if (null != qquser)
                {
                    var oauthuser = _oauth.Get(openid, OAuthType.QQ);
                    if (oauthuser != null && oauthuser.Id > 0)
                    {
                        var user = userinfo.Get(oauthuser.Uid);
                        if (user != null && user.Uid > 0)
                        {
                            oauthuser.AccessToken = access_token;
                            oauthuser.OutTime = DateTime.Now.AddSeconds(expires);
                            _oauth.Update(oauthuser);
                            return doLogin(user, null);
                        }
                    }
                    else {
                        Hashtable hash = new Hashtable();
                        hash["uname"] = qquser.nickname;
                        hash["header"] = qquser.figureurl_2;
                        hash["openid"] = openid;
                        hash["type"] = OAuthType.QQ;
                        hash["access_token"] = access_token;
                        hash["expires"] = expires;
                        Session["oauth_user"] = hash;
                        return RedirectToAction("BindOrReg");
                    }
                }
            }
            return ErrorInfo("未知错误!");
        }

        /// <summary>
        /// 账号绑定
        /// </summary>
        /// <returns></returns>
        public ActionResult BindOrReg()
        {
            ViewBag.user = Session["oauth_user"];
            return View();
        }

        /// <summary>
        /// 新浪微博登录
        /// </summary>
        /// <returns></returns>
        public ActionResult WeiboLogin()
        {
            SinaOAuth o = new SinaOAuth(ConfigurationManager.AppSettings["sina_weibo_key"], ConfigurationManager.AppSettings["sina_weibo_Secret"], ConfigurationManager.AppSettings["sina_weibo_Callback"]);
            Session["sina_oauth"] = o;
            return Redirect(o.ShwoLoginUrl());
        }

        /// <summary>
        /// 新浪微博返回地址
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ActionResult WeiboCallback(string code)
        {
            SinaOAuth o = Session["sina_oauth"] as SinaOAuth;
            if (o == null)
            {
                o = new SinaOAuth(ConfigurationManager.AppSettings["sina_weibo_key"], ConfigurationManager.AppSettings["sina_weibo_Callback"], ConfigurationManager.AppSettings["sina_weibo_Secret"]);
            }
            Session["sina_oauth"] = null;
            var accesstoken = o.GetAccessToken(code);
            SinaUser sinauser = o.GetUserInfo(accesstoken.Accesstoken, accesstoken.Uid);
            if (null != sinauser)
            {
                var oauthuser = _oauth.Get(accesstoken.Uid.ToString(), OAuthType.Weibo);
                if (oauthuser != null && oauthuser.Id > 0)
                {
                    var user = userinfo.Get(oauthuser.Uid);
                    if (user != null && user.Uid > 0)
                    {
                        oauthuser.AccessToken = accesstoken.Accesstoken;
                        oauthuser.OutTime = DateTime.Now.AddSeconds(accesstoken.Expires);
                        _oauth.Update(oauthuser);
                        return doLogin(user, null);
                    }
                }
                else
                {
                    Hashtable hash = new Hashtable();
                    hash["uname"] = sinauser.name;
                    hash["header"] = sinauser.avatar_large;
                    hash["openid"] = accesstoken.Uid;
                    hash["type"] = OAuthType.Weibo;
                    hash["access_token"] = accesstoken.Accesstoken;
                    hash["expires"] = accesstoken.Expires;
                    Session["oauth_user"] = hash;
                    return RedirectToAction("BindOrReg");
                }
            }

            return ErrorInfo("未知错误!");
        }

        /// <summary>
        /// 腾讯微博登入
        /// </summary>
        /// <returns></returns>
        public ActionResult QQWeiboLogin()
        {
            TxweiboOAuth weibo = new TxweiboOAuth(ConfigurationManager.AppSettings["tx_weibo_key"], ConfigurationManager.AppSettings["tx_weibo_Secret"], ConfigurationManager.AppSettings["tx_weibo_Callback"]);
            Session["tx_weibo"] = weibo;
            return Redirect(weibo.ShwoLoginUrl());
        }

        /// <summary>
        /// 腾讯微博返回
        /// </summary>
        /// <param name="code"></param>
        /// <param name="openid"></param>
        /// <param name="openkey"></param>
        /// <returns></returns>
        public ActionResult QQWeiboCallBack(string code, string openid, string openkey)
        {
            TxweiboOAuth weibo = Session["tx_weibo"] as TxweiboOAuth;
            if (weibo == null)
            {
                weibo = new TxweiboOAuth(ConfigurationManager.AppSettings["tx_weibo_key"], ConfigurationManager.AppSettings["tx_weibo_Secret"], ConfigurationManager.AppSettings["tx_weibo_Callback"]);
            }
            var accesstoken = weibo.GetAccessToken(code, openid, openkey);
            var txuser = weibo.GetUserInfo(openid, accesstoken.Accesstoken);
            try
            {
                if (null != txuser)
                {
                    var oauthuser = _oauth.Get(openid, OAuthType.TxWeibo);
                    if (oauthuser != null && oauthuser.Id > 0)
                    {
                        var user = userinfo.Get(oauthuser.Uid);
                        if (user != null && user.Uid > 0)
                        {
                            oauthuser.AccessToken = accesstoken.Accesstoken;
                            oauthuser.OutTime = DateTime.Now.AddSeconds(accesstoken.Expires);
                            _oauth.Update(oauthuser);
                            return doLogin(user, null);
                        }
                    }
                    else
                    {
                        Hashtable hash = new Hashtable();
                        hash["uname"] = txuser.nick;
                        hash["header"] = txuser.https_head;
                        hash["openid"] = openid;
                        hash["type"] = OAuthType.TxWeibo;
                        hash["access_token"] = accesstoken.Accesstoken;
                        hash["expires"] = accesstoken.Expires;
                        Session["oauth_user"] = hash;
                        return RedirectToAction("BindOrReg");
                    }
                }
            }
            catch (Exception ex)
            {
                return ErrorInfo(ex.Message);
            }
            return ErrorInfo("未知错误!");
        }
        #endregion

        #region 注册

        #region 注册页面
        /// <summary>
        /// 注册页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            return View();
        } 
        #endregion

        #region 注册
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="model"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public ActionResult DoRegister(RegisterModel model, string callback)
        {
            if (ModelState.IsValid)
            {
                if (model.UserName.IsUnameDirt())
                {
                    ModelState.AddModelError("UserName", "用户名包含非法字符！");
                }
                else
                {
                    var oauth = Session["oauth_user"] as Hashtable;
                    UserInfo bean = new UserInfo();
                    bean.Name = model.UserName;
                    bean.PassWord = DESCHandler.MD5_32(model.Password);
                    bean.Email = model.Email;
                    if (string.IsNullOrEmpty(bean.Header) && !string.IsNullOrEmpty(Request["header"]))
                    {
                        var header = StaticCs.SaveTempPic(StaticCs.DownImageToTemp(Request["header"]));
                        bean.Header = header;
                    }
                    userinfo.Add(bean);
                    LoginModel.SetUserInfo(bean);
                    if (oauth != null)
                    {
                        OAuthUser oath = new OAuthUser();
                        oath.Uid = bean.Uid;
                        oath.OpenId = oauth["openid"].ToString();
                        oath.Type = (OAuthType)oauth["type"];
                        oath.AccessToken = oauth["access_token"].ToString();
                        oath.OutTime = DateTime.Now.AddSeconds(Convert.ToInt64(oauth["expires"]));
                        _oauth.Add(oath);
                        Session["oauth_user"] = null;
                        StaticCs.RemoveUserFolder(bean.Uid);
                    }
                    if (!string.IsNullOrEmpty(callback))
                    {
                        return Redirect(callback);
                    }
                    else
                    {
                        return Redirect("/");
                    }
                }
            }
            return View("Register", model);
        } 
        #endregion

        #endregion

        #region 弹出登录窗口
        /// <summary>
        /// 弹出登录窗口
        /// </summary>
        /// <returns></returns>
        public ActionResult OpenBoxLogin()
        {
            return PartialView();
        } 
        #endregion

        #region 退出登录
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginOut()
        {
            Session.Clear();
            LoginModel.SetUserInfo(new UserInfo());
            Request.Cookies.Clear();
            Response.Buffer = true;
            Response.Expires = 0;
            Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
            Response.CacheControl = "no-cache";
            Response.AddHeader("Pragam", "No-Cache");
            return Redirect("/");
        } 
        #endregion

    }
}
